import { ACCESS_TOKEN, USER_INFO, PICK_ORDERS } from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'
import * as UserApi from '@/api/user'

// 登陆成功后执行
const loginSuccess = (commit, data) => {
  // 过期时间30天
  const expiryTime = 30 * 86400
  // 保存token到缓存
  storage.set(ACCESS_TOKEN, data.access_token, expiryTime)
  // 记录到store全局变量
  commit('SET_TOKEN', data.access_token)
  commit('SET_LOGIN_INFO', data)
}

const userSuccess = (commit, data) => {
  // 过期时间30天
  const expiryTime = 30 * 86400
  // 保存user到缓存
  storage.set(USER_INFO, data, expiryTime)
  // 记录到store全局变量
  commit('SET_USER_INFO', data)
}

const user = {
  state: {
    // 用户认证token
    token: '',
    // 登录信息
    loginInfo: {},
    // 用户信息
    userInfo: {},
    /**
     * 当前用户的会话消息，数据结构如下：<br/>
     * ```json
     * {
     *   [tenantId0]:
     *     "imPrivate_shopId0": [content0, content1, ...],
     *     "imPrivate_shopId1": [content0, content1, ...],
     *     ...,
     *     "imGroup_shopId0": [content0, content1, ...],
     *     "imGroup_shopId1": [content0, content1, ...],
     *     ...
     *   },
     *   ...
     * }
     * ```
     */
    messageUser: {},
    /**
     * 消息的maxId，数据结构如下：<br/>
     * ```json
     * {
     *   imPrivate_shopId0: maxId,
     *   imPrivate_shopId1: maxId,
     *   ...,
     *   imGroup_shopId0: maxId,
     *   imGroup_shopId1: maxId
     *   ...
     * }
     * ```
     */
    messageMaxId: {},
    /**
     * 维护未读消息的id，用于统计未读消息数量，数据结构如下：<br/>
     * ```json
     * {
     *   [tenantId0]: {
     *     [imPrivate_shopId0]: [messageId0, ...],
     *     ...,
     *     [imGroup_shopId0]: [messageId0, ...],
     *     ...
     *   }
     * }
     * ```
     */
    unreadMessageIds: {},
    /**
     * 私聊跳转会话详情时需携带的参数体，数据结构如下：<br/>
     * ```json
     * {
     *   channelLabel: '',
     *   channelColor: '',
     *   channelId: '',
     *   shopName: '',
     *   friendId: '',
     *   shopId: '',
     *   orderId: '',
     *   channelOrderNo: ''
     * }
     * ```
     */
    privateChatParams: {},
    /**
     * 消息底部导航展示的角标
     */
    tabbarBadge: 0,
    /**
     * 未读消息数量汇总（主要用于总部场景），数据结构如下：<br/>
     * ```json
     * {
     *   [tenantId0]: {
     *     [imAction0]: [],
     *     [imAction1]: []
     *   }
     * }
     * ```
     */
    masterShopUnReadMessageIds: {},
    // 全部门店
    shops: [],
    // 当前门店
    store: {},
    // 门店渠道
    channels: [],
    // 全部渠道
    allChannels: [],
    // 权限
    permissions: [],
    // 菜单
    menus:[],
    // 全部商户
    tenants: [],
    // 当前商户
    tenant: {},
    // 当前店铺
    counter: {},
    // 当前账号登录门店类型：0.总店，1.分店，2.店铺
    businessType: -1,
    // 自提点列表
    pickups:[],
    // 当前自提点
    pickup:{},
    // 拣货单配置
    pickConfig:{},
    // 拣货订单
    pickOrders: [],
    // 拣货员状态：0.非拣货员，1.休息，2.空闲，3.繁忙
    pickerStatus: 0,
    // 存储socket的普通消息
    socketAlertMessage: null
  },

  mutations: {
    SET_TOKEN: (state, value) => {
      state.token = value
    },
    SET_LOGIN_INFO: (state, value) => {
      state.loginInfo = value
    },
    SET_USER_INFO: (state, value) => {
      state.userInfo = value
    },
    SET_MESSAGE_USER: (state, value) => {
      state.messageUser = value
    },
    SET_MESSAGE_MAX_ID: (state, value) => {
      state.messageMaxId = value
    },
    SET_UNREAD_MESSAGE_IDS: (state, value) => {
      state.unreadMessageIds = value
    },
    SET_TABBAR_BADGE: (state, value) => {
      state.tabbarBadge = value
    },
    SET_PRIVATE_CHAT_PARAMS: (state, value) => {
      state.privateChatParams = value
    },
    SET_MASTER_SHOP_UNREAD_MESSAGE_IDS: (state, value) => {
      state.masterShopUnReadMessageIds = value
    },
    SET_SHOPS: (state, value) => {
      state.shops = value
    },
    SET_STORE: (state, value) => {
      state.store = value
    },
    SET_CHANNELS: (state, value) => {
      state.channels = value
    },
    SET_ALL_CHANNELS: (state, value) => {
      state.allChannels = value
    },
    SET_PERMISSIONS: (state, value) => {
      state.permissions = value
    },
    SET_MENUS: (state, value) => {
      state.menus = value
    },
    SET_TENANTS: (state, value) => {
      state.tenants = value
    },
    SET_TENANT: (state, value) => {
      state.tenant = value
    },
    SET_COUNTER: (state, value) => {
      state.counter = value
    },
    SET_BUSINESS_TYPE: (state, value) => {
      state.businessType = value
    },
    SET_PICKUPS: (state, value) => {
      state.pickups = value
    },
    SET_PICKUP: (state, value) => {
      state.pickup = value
    },
    SET_PICK_CONFIG: (state, value) => {
      state.pickConfig = value
    },
    SET_PICK_ORDERS: (state, value) => {
      storage.set(PICK_ORDERS, value)
      state.pickOrders = value
    },
    SET_PICKER_STATUS: (state, value) => {
      state.pickerStatus = value
    },
    SET_SOCKET_ALERT_MESSAGE: (state, value) => {
      state.socketAlertMessage = value
    }
  },

  actions: {

    // 用户登录 (普通登录: 输入手机号和验证码)
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.login(data)
          .then(response => {
            loginSuccess(commit, response)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 用户信息
    UserInfo({ commit }, data) {
      return new Promise((resolve, reject) => {
        UserApi.userInfo(data)
          .then(response => {
            const result = response.data
            const { permissions } = result
            userSuccess(commit, result)
            permissions && commit('SET_PERMISSIONS', permissions)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 退出登录
    Logout({ commit }, isHand) {
      const reset = () => {
        storage.remove(ACCESS_TOKEN)
        storage.remove(USER_INFO)
        storage.remove(PICK_ORDERS)
        // 记录到store全局变量
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', {})
        commit('SET_SHOPS', [])
        commit('SET_STORE', [])
        commit('SET_CHANNELS', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_COUNTER', {})
        commit('SET_PICK_ORDERS', [])
		commit('SET_PICKER_STATUS', 0)
        // 清除本地消息
        commit('SET_MESSAGE_USER', {})
        commit('SET_MESSAGE_MAX_ID', {})
        commit('SET_UNREAD_MESSAGE_IDS', {})
        commit('SET_TABBAR_BADGE', 0)
        commit('SET_PRIVATE_CHAT_PARAMS', {})
        commit('SET_MASTER_SHOP_UNREAD_MESSAGE_IDS', {})
        // 清除socket普通消息
        commit('SET_SOCKET_ALERT_MESSAGE', null)
        // 关闭IMSocket
        getApp().globalData.imWSInstance?.close()
      }
      return new Promise((resolve, reject) => {
        if (!isHand) {
          reset()
          return
        }
        LoginApi.logout().then(() => {
          reset()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
